package com.sk.coin.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sk.coin.model.R;
import com.sk.coin.sys.entity.SysPrivilege;
import com.sk.coin.sys.service.ISysPrivilegeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;

/**
 * @author: SongKun
 * @date: 2022/3/2
 * @Description: 权限管理控制器
 */
@RestController
@RequestMapping("/privileges")
@Api(tags = "权限管理")
public class SysPrivilegeController {

    @Autowired
    private ISysPrivilegeService sysPrivilegeService;

    @GetMapping
    @PreAuthorize("hasAuthority('sys_privilege_query')")
    @ApiOperation(value = "分页查询权限数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current" ,value = "当前页") ,
            @ApiImplicitParam(name = "size" ,value = "每页显示的大小") ,
    })
    public R<Page<SysPrivilege>> getPage(@ApiIgnore Page<SysPrivilege> page) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysPrivilege> sysPrivilegePage = sysPrivilegeService.page(page);
        return R.ok(sysPrivilegePage);
    }


    @ApiOperation(value = "新增一个权限")
    @PreAuthorize("hasAuthority('sys_privilege_create')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysPrivilege" ,value = "sysPrivilege 的json数据")
    })
    public R<?> add(@RequestBody @Validated SysPrivilege sysPrivilege){
        if(sysPrivilegeService.save(sysPrivilege)){
            return R.ok("新增成功") ;
        }
        return R.fail("新增失败") ;
    }

    @PatchMapping
    @PreAuthorize("hasAuthority('sys_privilege_update')")
    @ApiOperation(value = "修改一个权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysPrivilege" ,value = "sysPrivilege 的json数据")
    })
    public R<?> update(@RequestBody @Validated SysPrivilege sysPrivilege){
        if(sysPrivilegeService.updateById(sysPrivilege)){
            return R.ok("修改成功") ;
        }
        return  R.fail("修改失败") ;
    }

}
